package com.sunrise.gateway.commons;

import com.dap.utils.TraceIdUtils;
import com.sunrise.gateway.FrontendVersionManagerBase;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by wangmin on 2019/2/22.
 */
public class ResultContext {
    private String traceId;
    private String xToken;
    private String frontendVersion;

    public ResultContext() {
        this.traceId = TraceIdUtils.generateTraceId(false);
        this.xToken = SessionRequestExtraAuthUtil.resolveExtraAuthToken();

        HttpServletRequest httpRequest = GatewayServletContext.getHttpRequest();
        if (null != httpRequest) {
            String host = httpRequest.getHeader("host");
            if (!StringUtils.isEmpty(host)) {
                this.frontendVersion = FrontendVersionManagerBase.getFrontendVersion(host);
            }
        }
    }


    public String toJsonString() {
        StringBuilder sb = new StringBuilder("{");

        sb.append("\"traceId\":\"").append(traceId).append('"');

        if (null != xToken) {
            sb.append(",\"xToken\":");
            sb.append('"').append(xToken).append('"');
        }

        if (null != frontendVersion) {
            sb.append(",\"frontendVersion\":");
            sb.append('"').append(frontendVersion).append('"');
        }

        sb.append('}');

        return sb.toString();
    }
    @Override
    public String toString() {
        return toJsonString();
    }



    public void setTraceId(String traceId) {
        this.traceId = traceId;
    }
    public String getTraceId() {
        return traceId;
    }

    public String getxToken() {
        return xToken;
    }
    public void setxToken(String xToken) {
        this.xToken = xToken;
    }

    public String getFrontendVersion() {
        return frontendVersion;
    }
    public void setFrontendVersion(String frontendVersion) {
        this.frontendVersion = frontendVersion;
    }

}
